<?php

namespace App\Http\Controllers\Home;

use App\Http\Controllers\Controller;
use App\Http\Requests\Request;
use App\Http\Requests\UsersActiveRequest;
use App\Http\Requests\UsersRequest;
use App\Models\Admin\Users;
use App\Service\BankService;
use App\Service\HttpService;
use App\Service\UsersService;
use App\Traits\JsonResponse;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/*use Tymon\JWTAuth\Providers\AbstractServiceProvider;*/

class UsersController extends Controller
{
    use JsonResponse;

    /**
     * 1.周黑鸭手机号码查询是否注册了会员
     * @param HttpService $httpService
     * @return false|\Illuminate\Http\JsonResponse|string
     */
    public function memberCheck(HttpService $httpService)
    {

        $mobile = request(['mobile']);
        if (!$mobile) {
            return tips(-1, 'error', '参数错误');
        }
        // 验证手机号码
        if (!checkMobile($mobile['mobile'])) {
            return tips(-1, 'error', '手机号码错误');
        }
        Log::debug('memberCheck：mobile---' . json_encode($mobile));
        $params['phone'] = $mobile['mobile'];
        $params['sign'] = strtoupper(MD5("&phone=" . $mobile['mobile'] . "&key=" . config('app.zhy_config.key')));

        $params = http_build_query(($params));
        $url = config('app.zhy_config.member_check') . '?' . $params;

        try {
            $data = $httpService->HttpRequest($url, 'GET');
        } catch (\Exception $e) {
            return $this->errorReturn(10001, $e->getMessage());
        } catch (GuzzleException $e) {
            return $this->errorReturn(10001, $e->getMessage());
        }

        //“-1”-失败;0-该手机号码未注册会员；1-该手机号码注册了微信会员;2-该手机号码注册了支付宝会员;3-该手机号码同时注册了支付宝会员和微信会员
        if (isset($data['Statu'])) {
            if ($data['Statu'] == -1 ) {
                return tips($data['Statu'], 'error', $data['Msg']);
            } else {
                return tips($data['Statu'], 'success', $data['Msg']);
            }
        }
        return tips(-1, 'error', $data);

    }

    /**
     * 2.周黑鸭查询会员的手机号、openId、支付宝的userId、虚拟卡号
     * @param HttpService $httpService
     * @return false|\Illuminate\Http\JsonResponse|string
     */
    public function memberQuery(HttpService $httpService)
    {

        $queryStr = request(['queryStr']);
        if (!$queryStr) {
            return tips('error', '参数错误');
        }

        $params['querryStr'] = $queryStr['queryStr'];
        $params['sign'] = strtoupper(MD5("&querryStr=" . $queryStr['queryStr'] . "&key=" . config('app.zhy_config.key')));

        $params = http_build_query(($params));
        $url = config('app.zhy_config.member_query') . '?' . $params;
        Log::debug('memberQuery：queryStr---' . json_encode($queryStr['queryStr']));

        try {
            $data = $httpService->HttpRequest($url, 'GET');
        } catch (\Exception $e) {
            return $this->errorReturn(10001, $e->getMessage());
        } catch (GuzzleException $e) {
            return $this->errorReturn(10001, $e->getMessage());
        }

        //“-1”-失败;0-该手机号码未注册会员；1-该手机号码注册了微信会员;2-该手机号码注册了支付宝会员;3-该手机号码同时注册了支付宝会员和微信会员
        if (isset($data['Statu'])) {
            if ($data['Statu'] == -1) {
                return tips($data['Statu'], 'error', $data['Msg']);
            } else {
                return tips($data['Statu'], 'success', $data);
            }
        }
        return tips(1, 'success', $data);
    }

    /**
     * 3.周黑鸭 查询周黑鸭Crm会员
     * @param HttpService $httpService
     * @return false|\Illuminate\Http\JsonResponse|string
     */
    public function crmMemberQuery(HttpService $httpService)
    {
        $queryStr = request(['queryStr']);
        $queryType = request(['queryType']);
        if (!$queryStr || !$queryType) {
            return tips(-1, 'error', '参数错误');
        }

        $params['querryStr'] = $queryStr['queryStr'];
        $params['querryType'] = $queryType['queryType'];
        $params['sign'] = strtoupper(MD5("&querryStr=" . $queryStr['queryStr'] . "&querryType=" . $queryType['queryType']
            . "&key=" . config('app.zhy_config.key')));
        $params = http_build_query(($params));
        $url = config('app.zhy_config.crm_member_query') . '?' . $params;


        try {
            $data = $httpService->HttpRequest($url, 'GET');
        } catch (\Exception $e) {
            return $this->errorReturn(10001, $e->getMessage());
        } catch (GuzzleException $e) {

            return $this->errorReturn(10001, $e->getMessage());
        }

        //“-1”-失败;0-该手机号码未注册会员；1-该手机号码注册了微信会员;2-该手机号码注册了支付宝会员;3-该手机号码同时注册了支付宝会员和微信会员
        if (isset($data['Statu'])) {
            if ($data['Statu'] == -1) {
                return tips($data['Statu'], 'error', $data['Msg']);
            } else {
                return tips(1, 'success', $data);
            }
        }
        return tips(1, 'success', $data);
    }

    /**
     * 周黑鸭 会员注册
     * @param HttpService $httpService
     * @param UsersService $usersService
     * @return false|\Illuminate\Http\JsonResponse|string
     */
    public function memberRegister(HttpService $httpService, UsersService $usersService)
    {
        $Phone = request(['phone']);
        $Name = request(['name']);
        $Sex = request(['sex']);
        $Birthday = request(['birthday']);
        $ShopId = request(['shopID']);
        $Channel = request(['channel']);

      /*  $session_key = request('session_key')??'';
        $code = request('code')??'';
        if (!$session_key || !$code) {
            return tips(-1, 'error', '参数错误');
        }

        $params['sessionKey'] = $session_key;
        $params['verifyCode'] = $code;
        $params['sign'] = strtoupper(MD5("&sessionKey=" . $session_key."&verifyCode=" . $code . "&key=" . config('app.zhy_config.key')));

        $params = http_build_query($params);
        $url = config('app.zhy_config.verify_sms') . '?' . $params;

        try {
            $data = $httpService->HttpRequest($url, 'GET');
        } catch (\Exception $e) {
            return $this->errorReturn(10001, $e->getMessage());
        } catch (GuzzleException $e) {
            return $this->errorReturn(10001, $e->getMessage());
        }

        if (!$Phone || !$Name || !$Sex || !$Birthday || !$ShopId || !$Channel) {
            return tips(-1, 'error', '参数错误');
        }*/

        if (!checkMobile($Phone['phone'])) {
            return tips(-1, 'error', '手机号码格式不正确');
        }

        if (!in_array($Channel['channel'], ['ZC0401', 'ZC0402', 'ZC0403', 'appZC0404', 'ZC2005', 'ZC2006'])) {
            return tips(-1, 'error', '渠道错误');
        }

        $params['Phone'] = $Phone['phone'];

        $user = $usersService->getUsers($params['Phone']);
        if ($user) {
            return tips(-1, 'error', '请勿重复注册');
        }

        $params['Name'] = $Name['name'];
        $params['Sex'] = $Sex['sex'];
        $params['Birthday'] = $Birthday['birthday'];
        $params['ShopId'] = $ShopId['shopID'];
        $params['Channel'] = $Channel['channel'];
        $params['UserUniqueCode'] = rand(100000000,999999999);
        $params['Sign'] = strtoupper(
            MD5(
                "&Phone=" . $Phone['phone'] . "&Name=" . $Name['name']
                . "&Sex=" . $Sex['sex'] . "&Birthday=" . $Birthday['birthday']
                . "&Channel=" . $Channel['channel'] . "&ShopId=" . $ShopId['shopID']
                . "&Key=" . config('app.zhy_config.key')
            )
        );
        Log::debug('memberRegister：params---' . json_encode($params));

        $url = config('app.zhy_config.member_register');
        try {
            $data = $httpService->HttpRequest($url, 'POST', $params);

        } catch (\Exception $e) {
            return $this->errorReturn(10001, $e->getMessage());
        } catch (GuzzleException $e) {
            return $this->errorReturn(10001, $e->getMessage());
        }
        $data = \GuzzleHttp\json_decode($data, true);

        //“-1”-失败;0-该手机号码未注册会员；1-该手机号码注册了微信会员;2-该手机号码注册了支付宝会员;3-该手机号码同时注册了支付宝会员和微信会员
        if (isset($data['Statu'])) {
            if ($data['Statu'] == -1 || $data['Statu'] == 0) {
                return tips($data['Statu'], 'error', $data['Msg']);
            } else {
                $user = $usersService->getUsers($Phone['phone']);
                if (!$user) {
                    DB::beginTransaction();
                    try {
                        $userData = [
                            'mobile' => $Phone['phone'],
                            'name' => $Name['name'],
                            'sex' => $Sex['sex'] == '男' ? 1 : 2,
                            'birthday' => $Birthday['birthday'],
                            'shopId' => $ShopId['shopID'],
                            'channel' => $Channel['channel'],
                            'v_card_no' => $data['VCardNO'],
                            'user_unique_code' => $params['UserUniqueCode'],
                        ];
                        $addUsers = $usersService->store($userData);
                        if (!$addUsers) {
                            throw new \Exception('数据库操作异常');
                        }
                    } catch (\Exception $e) {
                        DB::rollBack();
                        return $this->errorReturn(10001, $e->getMessage());
                    }
                    DB::commit();
                    $datas['mobile'] = $Phone['phone'];
                    $datas['name'] = $Name['name'];
                    if (! $token = auth('api')->attempt($datas)) {
                        return response()->json(['error' => 'Unauthorized'], 401);
                    }

                    //$this->respondWithToken($token);
                    return tips(1, 'success', $this->respondWithToken($token));
                }
            }
        }
        $datas['mobile'] = $Phone['phone'];
        $datas['name'] = $Name['name'];

        if (! $token = auth('api')->attempt($datas)) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }

        return tips(1, 'success', $this->respondWithToken($token));
    }

    /**
     * 5.周黑鸭查询会员（返回余额积分）
     * @param HttpService $httpService
     * @return false|\Illuminate\Http\JsonResponse|string
     */
    public function memberQueryWithBalances(HttpService $httpService)
    {
        $queryStr = request(['queryStr']);
        if (!$queryStr) {
            return tips(-1, 'error', '参数错误');
        }

        $params['querryStr'] = $queryStr['queryStr'];
        $params['sign'] = strtoupper(MD5("&querryStr=" . $queryStr['queryStr'] . "&key=" . config('app.zhy_config.key')));

        $params = http_build_query(($params));
        $url = config('app.zhy_config.member_query_with_balance') . '?' . $params;

        try {
            $data = $httpService->HttpRequest($url, 'GET');
        } catch (\Exception $e) {
            return $this->errorReturn(10001, $e->getMessage());
        } catch (GuzzleException $e) {
            return $this->errorReturn(10001, $e->getMessage());
        }

        //“-1”-失败;0-该手机号码未注册会员；1-该手机号码注册了微信会员;2-该手机号码注册了支付宝会员;3-该手机号码同时注册了支付宝会员和微信会员
        if (isset($data['Statu'])) {
            if ($data['Statu'] == -1) {
                return tips($data['Statu'], 'error', $data['Msg']);
            } else {
                return tips(1, 'success', $data);
            }
        }

        return tips(1, 'success', $data);
    }

    /**
     * 6.周黑鸭 小程序根据Code获取会员信息
     * @param HttpService $httpService
     * @return false|\Illuminate\Http\JsonResponse|string
     */
    public function getMemberByCode(HttpService $httpService)
    {
        $code = request('code');
        $mobile = request('mobile');
        if (!$code || !$mobile) {
            return tips(-1, 'error', '参数错误');
        }

        $params['code'] = $code;
        $params['phone'] = $mobile;

        $params = http_build_query(($params));
        $url = config('app.zhy_config.get_member_by_code') . '?' . $params;

        try {
            $data = $httpService->HttpRequest($url, 'GET');
        } catch (\Exception $e) {
            return $this->errorReturn(10001, $e->getMessage());
        } catch (GuzzleException $e) {
            return $this->errorReturn(10001, $e->getMessage());
        }

        //“-1”-失败;0-该手机号码未注册会员；1-该手机号码注册了微信会员;2-该手机号码注册了支付宝会员;3-该手机号码同时注册了支付宝会员和微信会员
        if (isset($data['Statu'])) {
            if ($data['Statu'] == -1) {
                return tips($data['Statu'], 'error', $data['Msg']);
            } else {
                return tips(1, 'success', $data['Msg']);
            }
        }
        return tips(1, 'success', $data);
    }

    /**b
     *  周黑鸭crm会员订单列表
     * @param HttpService $httpService
     * @return false|\Illuminate\Http\JsonResponse|string
     */
    public function crmOrderList(HttpService $httpService){

        $openid = request('openid')??'';
        $page_index = request('page_index')??1;
        $page_size = request('page_size')??15;
        if(!$openid || !$page_index || !$page_size){
            return tips(-1,'error','参数错误');
        }
        $params['open_id'] = $openid;
        $params['page_index'] = $page_index;
        $params['page_size'] = $page_size;

        $params = http_build_query($params);

        $url = config('app.crm_order_list')."?".$params;

        try {
            $data = $httpService->HttpRequest($url, 'GET');
        } catch (\Exception $e) {
            return $this->errorReturn(10001, $e->getMessage());
        } catch (GuzzleException $e) {
            return $this->errorReturn(10001, $e->getMessage());
        }

        return tips(1,'success',$data);
    }

    /**
     *  周黑鸭发送验证码
     * @param HttpService $httpService
     * @return false|\Illuminate\Http\JsonResponse|string
     */
    public function sendSms(HttpService $httpService){
        $channel = request('channel')??'';
        $mobile = request('mobile')??'';
        if (!$channel || !$mobile) {
            return tips(-1, 'error', '参数错误');
        }

        $sign = strtoupper(MD5("&channel=" . $channel ."&phone=" . $mobile . "&key=" . config('app.zhy_config.key')));
        $url = config('app.zhy_config.send_sms') . "?phone=" . $mobile ."&channel=".$channel."&sign=".$sign;

        try {
            $data = $httpService->HttpRequest($url, 'GET');
        } catch (\Exception $e) {
            return $this->errorReturn(10001, $e->getMessage());
        } catch (GuzzleException $e) {
            return $this->errorReturn(10001, $e->getMessage());
        }

        return tips(1,'success',$data);
    }

    /**
     *  周黑鸭验证短信验证码
    */
    public function verifySms(HttpService $httpService){
        $session_key = request('session_key')??'';
        $code = request('code')??'';
        if (!$session_key || !$code) {
            return tips(-1, 'error', '参数错误');
        }

        $params['sessionKey'] = $session_key;
        $params['verifyCode'] = $code;
        $params['sign'] = strtoupper(MD5("&sessionKey=" . $session_key."&verifyCode=" . $code . "&key=" . config('app.zhy_config.key')));

        $params = http_build_query($params);
        $url = config('app.zhy_config.verify_sms') . '?' . $params;

        try {
            $data = $httpService->HttpRequest($url, 'GET');
        } catch (\Exception $e) {
            return $this->errorReturn(10001, $e->getMessage());
        } catch (GuzzleException $e) {
            return $this->errorReturn(10001, $e->getMessage());
        }

        return tips(1,'success',$data);
    }

    /**
     * 12.批量获取券码
     * @param HttpService $httpService
     * @return false|\Illuminate\Http\JsonResponse|string
     */
    public function getCoupons(HttpService $httpService){
        $pubid = request('pubid')??'';
        $count = request('count')??'';
        if (!$pubid || !$count) {
            return tips(-1, 'error', '参数错误');
        }

        $params['pubid'] = $pubid;
        $params['count'] = $count;
        $params['sign'] = strtoupper(MD5("&pubid=" . $pubid."&count=" . $count . "&key=" . config('app.zhy_config.key')));
        $params = http_build_query($params);
        $url = config('app.zhy_config.coupons') . '?' . $params;
        try {
            $data = $httpService->HttpRequest($url, 'GET');
        } catch (\Exception $e) {
            return $this->errorReturn(10001, $e->getMessage());
        } catch (GuzzleException $e) {
            return $this->errorReturn(10001, $e->getMessage());
        }

        return tips(1,'success',$data);
    }

    /**
     * 获取用户个人信息
     * @param UsersService $users
     * @return \Illuminate\Http\JsonResponse
     */
    public function userInfo(UsersService $users)
    {
        $user_id = isset(auth()->user('api')->id) ? auth()->user('api')->id : false;
        if (!$user_id) {
            return tips(-1, 'error', '');
        }

        $userInfo = $users->getUserList(['id', 'avatar', 'name', 'birthday', 'mobile', 'area'], ['id' => $user_id]);
        return tips(1, 'success', $userInfo[0]);
    }

    /**
     * 会员绑定的银行卡列表
     * @param BankService $bankService
     * @return \Illuminate\Http\JsonResponse
     */
    public function bankList(BankService $bankService)
    {
        $user_id = isset(auth()->user('api')->id) ? auth()->user('api')->id : false;
        if (!$user_id) {
            return tips(-1, 'error', '');
        }

        $bank = $bankService->getBankList(['account', 'bank', 'id', 'mobile'], ['user_id' => $user_id]);
        if (count($bank) > 0) {
            foreach ($bank as $key => $value) {
                $bank[$key]->account = substr_replace($value->account, '**** **** **** ***', 0, -4);
            }
        }
        return tips(1, 'success', $bank);
    }

    // 要验证码稍微缓缓
    public function bindBank(){
        $user_id = isset(auth()->user('api')->id) ? auth()->user('api')->id : false;
        if (!$user_id) {
            return tips(-1, 'error', '');
        }
    }

    public function setWithdrawalPassword(Request $request){

        $user_id = isset(auth()->user('api')->id) ? auth()->user('api')->id : false;
        if (!$user_id) {
            return tips(-1, 'error', '');
        }

        $params = $request->except(['_token']);

        if(!empty($params['withdrawal_pwd'])){
            $params['withdrawal_pwd'] = \Hash::make($params['withdrawal_pwd']);
        }


        dd($params);
    }


    /**
     *
     * @param $token
     * @return \Illuminate\Http\JsonResponse
     * @author Bryant
     * @date 2020-09-02 10:17
     *
     * 获取token
     */
    protected function respondWithToken($token)
    {
        return response()->json([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth('api')->factory()->getTTL() * 60
        ]);
    }

    /**
     *
     * @author Bryant
     * @date 2020-10-22 14:27
     *
     *
     */
    public function textSoap()
    {
        $nums = rand(100000,999999);
        // 获取CRM 的数据
        $getUrl = "http://8.129.17.60:8898"; //C# 中间件的访问地址
        $param = [
            'action' => 'ZRFC_INTERACTIONPOINTS_PAY', //访问的方法
            'ZZCHANNEL' => "HNX", // 渠道
            'PARTNER_ID' =>'1001128776', // 会员号
            'MOB_NUMBER' =>"",
            'ZZAUART' => 'S02',
            'ZZVBELN' => date('YmdHis',time()).$nums,
            'ZZCPSYDAT' => date('YmdHis',time()),
            'ZEPOINT_ADD' => 1,
            'ZEPOINT_RED' => '',
            'ZEPRODUCTS_ID' => 'HDJF',
            'ZZCPSTORE' => "WH00001",

        ];
        $param = json_encode($param,true);

        $res = $this->curl_open($getUrl,$param);

        if ($res['errcode'] == 4002) {

            $res = $this->curl_open($getUrl,$param);
        }

        dd($res);

    }


}
